package com.radar.utils;

import org.meteoinfo.legend.ColorBreak;
import org.meteoinfo.legend.LegendScheme;
import ucar.nc2.Attribute;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

public class MyNcUtil {

    private static String LGS_PATH = File.separator + "lgs" + File.separator + "color" + File.separator;

    public static void readrToImageSave2(double[][] data, String lgs, String imagePath, String imageName, String suffix) {
        try {
//            GridData grid = meteo.getGridData();
//            double[][] data = grid.getData();
            int[] TEMShape = new int[]{data.length, data[0].length};
            //读取色阶
            LegendScheme legendScheme = new LegendScheme();
            String property = System.getProperty("user.dir");
            legendScheme.importFromXMLFile(property + LGS_PATH + lgs);//temp_GraduatedColor.lgs"
            List<ColorBreak> legendBreaks = legendScheme.getLegendBreaks();
            BufferedImage b = new BufferedImage(TEMShape[1], TEMShape[0], BufferedImage.TYPE_INT_RGB);
            // ----------  增加下面的代码使得背景透明  -----------------
            Graphics2D g = b.createGraphics();
            b = g.getDeviceConfiguration().createCompatibleImage(TEMShape[1], TEMShape[0], Transparency.TRANSLUCENT);
            g.dispose();
            g = b.createGraphics();
            // ----------  背景透明代码结束  -----------------
            Color[][] arr = new Color[TEMShape[1]][TEMShape[0]];
            for (int m = 0; m < TEMShape[0]; m++) {
                for (int n = 0; n < TEMShape[1]; n++) {
                    double temValue = data[TEMShape[0] - 1 - m][n];
//                    temValue = (temValue - 66) / 2;

                    for (ColorBreak colorBreak : legendBreaks) {
                        Double startValue = Double.valueOf(colorBreak.getStartValue().toString());
                        Double endValue = Double.valueOf(colorBreak.getEndValue().toString());
                        if (temValue >= startValue && temValue < endValue) {
                            Color color = colorBreak.getColor();
                            int blue = color.getBlue();
                            int red = color.getRed();
                            int green = color.getGreen();
                            Color resultColor = new Color(red, green, blue, 128);
                            arr[n][m] = resultColor;
                            g.setColor(arr[n][m]);
                            g.fillRect(n, m, 1, 1);
                        }
                    }
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imagePath+File.separator + imageName + "." + suffix));//"D:\\work\\image\\"
            ImageIO.write(b, suffix, fileOutputStream);
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 格点日平均温度实况数据
     * 格点日最低温度实况数据
     * 格点日最高温度实况数据
     * 格点日累计雨量实况数据
     * 格点逐小时最低温度实况数据
     * 格点逐小时最高温度实况数据
     * 格点逐小时降雨量实况数据
     * 格点逐小时的小时累计降水量实况数据
     * 格点逐小时湿度实况数据
     * 格点逐小时气压实况数据
     * 格点逐小时土壤湿度（0-10cm）实况数据
     * 格点逐小时土壤湿度（0-20cm）实况数据
     * 格点逐小时土壤湿度（0-50cm）实况数据
     * 格点逐小时2分钟平均风速实况数据
     * 格点逐小时10分钟平均风速实况数据
     * 格点逐小时极大风速实况数据
     *
     * @param ncFile
     * @param elementName
     * @param lgs
     * @param imagePath
     * @param imageName
     * @param suffix
     */
    public static boolean dayTNcToImageSave(NetcdfFile ncFile, String elementName, String lgs, String imagePath, String imageName, String suffix) {
        try {
            Variable TEM = ncFile.findVariable(elementName);//读取的要素
            Attribute tem_scale_factor = TEM.findAttribute("scale_factor");
            float tem_value = 1.0F;
            double[][] TEMList = (double[][]) TEM.read().copyToNDJavaArray();
            int[] TEMShape = TEM.getShape();
            //读取色阶
            LegendScheme legendScheme = new LegendScheme();
            String property = System.getProperty("user.dir");
            legendScheme.importFromXMLFile(property + LGS_PATH + lgs);//temp_GraduatedColor.lgs"
            List<ColorBreak> legendBreaks = legendScheme.getLegendBreaks();

            BufferedImage b = new BufferedImage(TEMShape[1], TEMShape[0], BufferedImage.TYPE_INT_RGB);
            // ----------  增加下面的代码使得背景透明  -----------------
            Graphics2D g = b.createGraphics();
            b = g.getDeviceConfiguration().createCompatibleImage(TEMShape[1], TEMShape[0], Transparency.TRANSLUCENT);
            g.dispose();
            g = b.createGraphics();
            // ----------  背景透明代码结束  -----------------
            Color[][] arr = new Color[TEMShape[1]][TEMShape[0]];
            for (int m = 0; m < TEMShape[0]; m++) {
                for (int n = 0; n < TEMShape[1]; n++) {
                    double temfloatValue = TEMList[TEMShape[0] - 1 - m][n] * tem_value;
                    for (ColorBreak colorBreak : legendBreaks) {
                        Double startValue = Double.valueOf(colorBreak.getStartValue().toString());
                        Double endValue = Double.valueOf(colorBreak.getEndValue().toString());
                        if (temfloatValue > startValue && temfloatValue < endValue) {
                            Color color = colorBreak.getColor();
                            int blue = color.getBlue();
                            int red = color.getRed();
                            int green = color.getGreen();
                            Color resultColor = new Color(red, green, blue, 128);
                            arr[n][m] = resultColor;
                            g.setColor(arr[n][m]);
                            g.fillRect(n, m, 1, 1);
                        }
                    }

                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imagePath + imageName + "." + suffix));//"D:\\work\\image\\"
            ImageIO.write(b, suffix, fileOutputStream);
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 网格数据，画图
     *
     * @param ncFile
     * @param elementName
     * @param lgs
     * @param imagePath
     * @param imageName
     * @param suffix
     */
    public static void ncToImageSave(NetcdfFile ncFile, String elementName, String lgs, String imagePath, String imageName, String suffix) {
        try {
            Variable TEM = ncFile.findVariable(elementName);//读取的要素
            Attribute tem_scale_factor = TEM.findAttribute("scale_factor");
            float tem_value = 0.1f;
            if (tem_scale_factor!=null){
                tem_value = (float) tem_scale_factor.getValue(0);
            }
            short[][] TEMList = (short[][]) TEM.read().copyToNDJavaArray();
            int[] TEMShape = TEM.getShape();
            //读取色阶
            LegendScheme legendScheme = new LegendScheme();
            String property = System.getProperty("user.dir");
            legendScheme.importFromXMLFile(property + LGS_PATH + lgs);//temp_GraduatedColor.lgs"
            List<ColorBreak> legendBreaks = legendScheme.getLegendBreaks();

            BufferedImage b = new BufferedImage(TEMShape[1], TEMShape[0], BufferedImage.TYPE_INT_RGB);
            // ----------  增加下面的代码使得背景透明  -----------------
            Graphics2D g = b.createGraphics();
            b = g.getDeviceConfiguration().createCompatibleImage(TEMShape[1], TEMShape[0], Transparency.TRANSLUCENT);
            g.dispose();
            g = b.createGraphics();
            // ----------  背景透明代码结束  -----------------
            Color[][] arr = new Color[TEMShape[1]][TEMShape[0]];
            for (int m = 0; m < TEMShape[0]; m++) {
                for (int n = 0; n < TEMShape[1]; n++) {
                    Short temValue = TEMList[TEMShape[0] - 1 - m][n];
                    float temfloatValue = temValue * tem_value;

                    for (ColorBreak colorBreak : legendBreaks) {
                        Double startValue = Double.valueOf(colorBreak.getStartValue().toString());
                        Double endValue = Double.valueOf(colorBreak.getEndValue().toString());
                        if (temfloatValue >= startValue && temfloatValue < endValue) {
                            Color color = colorBreak.getColor();
                            int blue = color.getBlue();
                            int red = color.getRed();
                            int green = color.getGreen();
                            Color resultColor = new Color(red, green, blue, 128);
                            arr[n][m] = resultColor;
                            g.setColor(arr[n][m]);
                            g.fillRect(n, m, 1, 1);
                        }
                    }
//                    g.setColor(arr[n][m]);
//                    g.fillRect(n, m, 1, 1);
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imagePath + imageName + "." + suffix));//"D:\\work\\image\\"
            ImageIO.write(b, suffix, fileOutputStream);
            fileOutputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 辐射色谱
     *
     * @param dbz
     * @return
     */
    public static Color GetColorByDBZ(double dbz) {
        Color t_clr = new Color(255, 255, 255, 255); //有值无回波，可自定义透明度
        if (dbz >= 10 && dbz < 15) {
            t_clr = new Color(8, 161, 244, 255); //透明度   R  G B
        } else if (dbz >= 15 && dbz < 20) {
            t_clr = new Color(0, 236, 236, 255);
        } else if (dbz >= 20 && dbz < 25) {
            t_clr = new Color(0, 216, 0, 255);
        } else if (dbz >= 25 && dbz < 30) {
            t_clr = new Color(0, 144, 0, 255);
        } else if (dbz >= 30 && dbz < 35) {
            t_clr = new Color(255, 255, 0, 255);
        } else if (dbz >= 35 && dbz < 40) {
            t_clr = new Color(231, 192, 0, 255);
        } else if (dbz >= 40 && dbz < 45) {
            t_clr = new Color(255, 144, 0, 255);
        } else if (dbz >= 45 && dbz < 50) {
            t_clr = new Color(255, 0, 0, 255);
        } else if (dbz >= 50 && dbz < 55) {
            t_clr = new Color(214, 0, 0);
        } else if (dbz >= 55 && dbz < 60) {
            t_clr = new Color(192, 0, 0);
        } else if (dbz >= 60 && dbz < 65) {
            t_clr = new Color(255, 0, 240);
        } else if (dbz >= 65 && dbz < 70) {
            t_clr = new Color(150, 0, 180);
        } else if (dbz >= 70 && dbz < 100) {
            t_clr = new Color(173, 144, 240);
        } else if (dbz < 0) //无值--缺测值
        {
            t_clr = new Color(255, 255, 255, 255); //有值无回波，可自定义透明度
//            t_clr = new Color(30, 0, 0, 0);
        }
        return t_clr;
    }

}
